<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{Agent,Fukalist, BusinessCommu, BusinessType, PlatSons, AgentCommu, IntergralLog, UserCommu, UserCommuDetail, Recpeople, RecpeopleLeimu, RecpeopleCommu, BussinessSq, AgentArea, Wechat, User as Users, Business, Address, Region, Cart, Goods, GoodsSpec, Order, OrderGoods, Coupon, UserLevel, BusinessArea, Compent, Payment, Pkey, Promo, Apply, MoneyLog, Config};
use think\Facade\Config as Configs;
use EasyWeChat\Factory;
use think\Validate;
use think\Db;
use think\facade\Log;

class User extends Base
{

    public function updateinfo()
    {
        $data = $this->request->post();
        $type = $data['type'] ?? 0;
        if ($type == 0) {
            $validate = new Validate([
                'avatarUrl' => 'require',
                'nickName' => 'require',
            ], [
                'avatarUrl.require' => '头像不能为空',
                'nickName.require' => '昵称不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $res = (new Users())->where('id', $this->request->user_id)->update(['avatarUrl' => $data['avatarUrl'], 'nickName' => $data['nickName']]);
        } elseif ($type == 1) {
            $validate = new Validate([
                'password' => 'require',
                'opassword' => 'require',
            ], [
                'password.require' => '头像不能为空',
                'opassword.require' => '昵称不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if ($data['password'] != $data['opassword']) {
                $this->result([], 1, '密码输入不一致请重新输入');
            }
            $res = (new Users())->where('id', $this->request->user_id)->update(['opassword' => $data['opassword'], 'password' => md5(md5($data['password']))]);
        }
        if ($res) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败');
    }

    public function loginmobile()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'account' => 'require',
            'passwords' => 'require',
        ], [
            'account.require' => '手机号不能为空',
            'passwords.require' => '密码不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $user = (new Users())->where('mobile', $data['account'])->find();
        if (empty($user)) {
            $this->result([], 1, '账号不存在');
        }
        if (md5(md5($data['passwords'])) != $user['password']) {
            $this->result([], 1, '密码不正确');
        }
        $token = 'user_' . md5(time() . $user['code']);
        Redis::setex($token, 7 * 86400, $user['id']);
        $this->result(['token' => $token], 0, '登录成功');
    }

    public function fuka()
    {
        $list = config()['config']['fktype'];
        $list[0] = '精选推荐';
        $result = [];
        foreach ($list as $k => $v) {
            if (!empty($k)) {
                $fuka = (new Fukalist())->order('sort desc')->where('type', $k)->select();
            } else {
                $fuka = (new Fukalist())->order('sort desc')->select();
            }
            foreach ($fuka as $ka) {
                //2表示跳转其他小程序 1表示跳转本地页 其他不跳转
                $level = $this->request->user['level'] ?? 1;
                $ka['level'] = $level;
                if (!empty($ka['appid']) && !empty($ka['path'])) {
                    $ka['quan'] = 2;
                } elseif (!empty($ka['path'])) {
                    $ka['quan'] = 1;
                } else {
                    $ka['quan'] = 0;
                }
            }
            if (count($fuka)) {
                $result[] = [
                    'id' => $k,
                    'name' => $v,
                    'list' => $fuka
                ];
            }
        }
        $result =  array_reverse($result);
        $this->result($result, 0, '查询完成');
    }

    public function pinglun()
    {
        $type = $this->request->get('type/d', 1); //1我的评论 2评论我的
        if ($type == 1) {
            $list = (new UserCommuDetail())->where(['user_id' =>  $this->request->user_id, 'status' => 1, 'type' => 2])->paginate(20, false, ['query' => $this->request->param()]);
            foreach ($list as $row) {
                $commu = (new UserCommu())->where('id', $row['usercommuid'])->find();
                $commu['images'] = json_decode(($commu['images'] ?? ''), true) ?? [];
                $row['usercommu'] = $commu;
            }
        } else {
        }
        $this->result($list, 0, '查询完成');
    }

    public function comdetaildel()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'type' => 'require|in:1,2', //1删帖 2删评论
                'id' => 'require',
            ], [
                'type.require' => '类型不能为空',
                'type.in' => '类型不正确',
                'id.require' => 'ID不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if ($data['type'] == 1) {
                $model =  (new UserCommu());
            } else {
                $model =  (new UserCommuDetail());
            }
            $row = $model->where(['id' => $data['id'], 'user_id' => $this->request->user_id])->find();
            if (empty($row)) {
                $this->result([], 1, '资源不存在或已删除');
            }
            $res = $model->where('id', $data['id'])->update(['status' => 2]);
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败，请重试');
        }
    }

    public function getusercommulist()
    {
        $utype = $this->request->get('utype/d', 0);
        switch ($utype) {
            //我的帖子
            case '1':
                $typeid = $this->request->get('type/d', 0);
                $list = (new UserCommu())->order('id desc');
                if (!empty($typeid)) {
                    $list = $list->where('type', $typeid);
                }
                $list = $list->where(['user_id' =>  $this->request->user_id, 'status' => 1]);
                $list = $list->paginate(20, false, ['query' => $this->request->param()]);
                foreach ($list as $row) {
                    $row['images'] = json_decode($row['images'], true) ?? [];
                    $row['zan'] = (new UserCommuDetail())->where(['status' => 1, 'type' => 1, 'usercommuid' => $row['id']])->count();
                    $row['comment'] = (new UserCommuDetail())->where(['status' => 1, 'type' => 2, 'usercommuid' => $row['id']])->count();
                    $mobile = (new Users())->where('id', $row['user_id'])->value('mobile') ?? '';
                    $row['mobile'] = preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i', '$1****$2', $mobile);
                }
                break;
            //我的点赞
            case '2':
                $usercommuid = (new UserCommuDetail())->where(['user_id' =>  $this->request->user_id, 'status' => 1, 'type' => 1])->column('usercommuid') ?? [];
                $list = (new UserCommu())->order('id desc');
                if (empty($usercommuid)) {
                    $list = $list->where(['id' => 0]);
                } else {
                    $list = $list->where(['id' => $usercommuid]);
                }
                $list = $list->where(['status' => 1]);
                $list = $list->paginate(20, false, ['query' => $this->request->param()]);
                foreach ($list as $row) {
                    $row['images'] = json_decode($row['images'], true) ?? [];
                    $row['zan'] = (new UserCommuDetail())->where(['status' => 1, 'type' => 1, 'usercommuid' => $row['id']])->count();
                    $row['comment'] = (new UserCommuDetail())->where(['status' => 1, 'type' => 2, 'usercommuid' => $row['id']])->count();
                    $mobile = (new Users())->where('id', $row['user_id'])->value('mobile') ?? '';
                    $row['mobile'] = preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i', '$1****$2', $mobile);
                }
                break;
            //我的评论
            case '3':
                $list = (new UserCommuDetail())->order('id desc');
                $list = $list->where(['status' => 1, 'user_id' => $this->request->user_id, 'type' => 2]);
                $list = $list->paginate(20, false, ['query' => $this->request->param()]);
                foreach ($list as $row) {
                    //查找相关帖子
                    $tiezi = (new UserCommu())->where('id', $row['usercommuid'])->find();
                    if ($tiezi) {
                        $tiezi['images'] = json_decode($tiezi['images'], true) ?? [];
                    }
                    $row['tiezi'] = $tiezi;
                    //被回复帖子
                    if (!empty($row['sdetailid'])) {
                        $replytiezi = (new UserCommuDetail())->where('id', $row['sdetailid'])->find();
                        if (!empty($replytiezi)) {
                            $row['reply_text'] = $replytiezi['texts'] ?? '信息已删除';
                            $mobile = (new Users())->where('id', $replytiezi['user_id'])->value('mobile') ?? '';
                            $row['reply_mobile'] = preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i', '$1****$2', $mobile);
                        }
                    }
                }
                break;
            //我的通知
            case '4':
                $list = (new UserCommuDetail())->order('id desc');
                $list = $list->where(['status' => 1, 'touser_id' => $this->request->user_id, 'type' => 2]);
                $list = $list->paginate(20, false, ['query' => $this->request->param()]);
                foreach ($list as $row) {
                    //查找相关帖子
                    $tiezi = (new UserCommu())->where('id', $row['usercommuid'])->find();
                    if ($tiezi) {
                        $tiezi['images'] = json_decode($tiezi['images'], true) ?? [];
                    }
                    $row['tiezi'] = $tiezi;
                    //被回复帖子
                    if (!empty($row['sdetailid'])) {
                        $replytiezi = (new UserCommuDetail())->where('id', $row['sdetailid'])->find();
                        if (!empty($replytiezi)) {
                            $row['reply_text'] = $replytiezi['texts'] ?? '信息已删除';
                            $mobile = (new Users())->where('id', $replytiezi['user_id'])->value('mobile') ?? '';
                            $row['reply_mobile'] = preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i', '$1****$2', $mobile);
                        }
                    }
                }
                break;
            default:
                $typeid = $this->request->get('type/d', 0);
                $xiaoquid = $this->request->get('xiaoquid/d', 0);
                $list = (new UserCommu())->order(['id' => 'desc', 'readall' => 'desc']);
                $title = $this->request->get('keyword');
                if (!empty($typeid)) {
                    $list = $list->where('type', $typeid);
                }
                if (!empty($title)) {
                    $list = $list->where('title|descs|contents', 'like', '%' . $title . '%');
                }
                $list = $list->where(['xiaoquid' =>  $xiaoquid, 'status' => 1]);
                $list = $list->paginate(20, false, ['query' => $this->request->param()]);
                foreach ($list as $row) {
                    $row['images'] = json_decode($row['images'], true) ?? [];
                    $row['zan'] = (new UserCommuDetail())->where(['status' => 1, 'type' => 1, 'usercommuid' => $row['id']])->count();
                    $row['comment'] = (new UserCommuDetail())->where(['status' => 1, 'type' => 2, 'usercommuid' => $row['id']])->count();
                    $mobile = (new Users())->where('id', $row['user_id'])->value('mobile') ?? '';
                    $row['mobile'] = preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i', '$1****$2', $mobile);
                }
                break;
        }
        $this->result($list, 0, '查询完成');
    }



    public function comdetail()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            switch ($data['type']) {
                case '1':
                    $validate = new Validate([
                        'usercommuid' => 'require'
                    ], [
                        'usercommuid.require' => '帖子不能为空'
                    ]);
                    if (!$validate->check($data)) {
                        $this->result([], 1, $validate->getError());
                    }
                    $detail = (new UserCommuDetail())->where(['user_id' => $this->request->user_id, 'type' => 1, 'usercommuid' => $data['usercommuid']])->find();
                    $details = ['user_id' => $this->request->user_id, 'type' => 1, 'usercommuid' => $data['usercommuid'], 'status' => 1];
                    if (empty($detail)) {
                        $res = (new UserCommuDetail())->allowfield(true)->save($details);
                    } else {
                        if ($detail['status'] == 1) {
                            $details['status'] = 2;
                        } else {
                            $details['status'] = 1;
                        }
                        $res = (new UserCommuDetail())->allowfield(true)->save($details, ['id' => $detail['id']]);
                    }
                    if ($res) {
                        $this->result([], 0, '操作成功');
                    }
                    $this->result([], 1, '操作失败，请重试');
                    break;
                case '2':
                    $validate = new Validate([
                        'usercommuid' => 'require',
                        'texts' => 'require',

                    ], [
                        'usercommuid.require' => '帖子ID不能为空',
                        'texts.require' => '帖子内容不能为空',
                    ]);
                    if (!$validate->check($data)) {
                        $this->result([], 1, $validate->getError());
                    }

                    $details = [
                        'detailid' => 0,
                        'sdetailid' => $data['sdetailid'],
                        'texts' => $data['texts'],
                        'user_id' => $this->request->user_id,
                        'touser_id' => 0,
                        'type' => 2,
                        'usercommuid' => $data['usercommuid'],
                        'status' => 1
                    ];
                    if (!empty($data['sdetailid'])) {
                        $userdetails = (new UserCommuDetail())->where(['id' => $data['sdetailid'], 'type' => 2])->find();
                        if (empty($userdetails)) {
                            $this->result([], 1, '该评论已删除');
                        }
                        $details['touser_id'] = $userdetails['user_id'] ?? 0;
                        if (empty($userdetails['detailid'])) {
                            $details['detailid'] = $userdetails['id'];
                        } else {
                            $details['detailid'] = $userdetails['detailid'];
                        }
                    } else {
                        $usercommu = (new UserCommu())->where(['id' => $data['usercommuid']])->find();
                        $details['touser_id'] = $usercommu['user_id'] ?? 0;
                    }
                    $res = (new UserCommuDetail())->allowfield(true)->save($details);
                    if ($res) {
                        $this->result([], 0, '操作成功');
                    }
                    $this->result([], 1, '操作失败，请重试');
                    break;
                default:
                    # code...
                    break;
            }
        } else {
            $id = $this->request->get('id/d', 0);
            $list = (new UserCommuDetail())->where(['usercommuid' => $id, 'detailid' => 0, 'status' => 1, 'type' => 2])->select();
            foreach ($list as $row) {
                $mobile = (new Users())->where('id', $row['user_id'])->value('mobile') ?? '未知用户';
                $row['mobile'] = preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i', '$1****$2', $mobile);
                $sonlist = (new UserCommuDetail())->where(['usercommuid' => $id, 'detailid' => $row['id'], 'status' => 1, 'type' => 2])->select();
                //下级评论
                foreach ($sonlist as $slist) {
                    $smobile = (new Users())->where('id', $slist['user_id'])->value('mobile') ?? '';
                    $slist['mobile'] = preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i', '$1****$2', $smobile);
                    $slist['r_mobile'] = '';
                    if ($slist['sdetailid'] > 0 && $slist['sdetailid'] != $slist['id']) {
                        $r_user_id = (new UserCommuDetail())->where(['id' => $slist['sdetailid']])->value('user_id');
                        $s_u_mobile = (new Users())->where('id', $r_user_id)->value('mobile') ?? '未知用户';
                        $slist['r_mobile'] = preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i', '$1****$2', $s_u_mobile);
                    }
                }
                $row['list'] = $sonlist;
            }
            $this->result($list, 0, '查询完成');
        }
    }

    public function putcommu()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'type' => 'require|in:1,2',
                'xiaoquid' => 'require|gt:0',
                'title' => 'require',
                'images' => 'require',
            ], [
                'type.require' => '活动(发帖)类型不能为空',
                'type.in' => '活动(发帖)类型不正确',
                'xiaoquid.require' => '小区ID不能为空',
                'xiaoquid.gt' => '小区ID必须大于0',
                'title.require' => '活动(发帖)标题不能为空',
                'images.require' => '活动(发帖)主图不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (empty($data['images'])) {
                $this->result([], 1, '发帖主图不能为空');
            }
            $data['images'] = json_encode($data['images'], true) ?? '';
            if ($data['type'] == 1) {
                $data['descs'] = $data['descs'] ?? '';
                $data['contents'] = '';
                if (mb_strlen($data['descs']) < 15) {
                    $this->result([], 1, '内容长度不能低于15个字符');
                }
            }
            if ($data['type'] == 2) {
                if (empty($data['startime'])) {
                    $this->result([], 1, '活动开始时间不能为空');
                }
                if (empty($data['endtime'])) {
                    $this->result([], 1, '活动结束时间不能为空');
                }
                $data['descs'] = '';
                $data['contents'] = $data['contents'] ?? '';
                if (mb_strlen($data['contents']) < 15) {
                    $this->result([], 1, '内容长度不能低于15个字符');
                }
            }
            if (empty($data['id'])) {
                $data['user_id'] = $this->request->user_id;
                $res = (new UserCommu())->allowfield(true)->save($data);
            } else {
                $res = (new UserCommu())->allowfield(true)->save($data, ['id' => $data['id']]);
            }
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败，请重试');
        } else {
            $id = $this->request->get('id/d', 0);
            $results = (new UserCommu())->where(['id' => $id])->find();
            $user_id = (int)$this->request->user_id ?? 0;
            if ($results) {
                $results['images'] = json_decode($results['images'], true) ?? [];
                $results['zan'] = (new UserCommuDetail())->where(['status' => 1, 'type' => 1, 'usercommuid' => $results['id']])->count();
                $results['comment'] = (new UserCommuDetail())->where(['status' => 1, 'type' => 2, 'usercommuid' => $results['id']])->count();
                $results['youzan'] = (new UserCommuDetail())->where(['user_id' => $user_id, 'status' => 1, 'type' => 1, 'usercommuid' => $results['id']])->count();
                $rdsname = 'commuid_' . $id . $user_id;
                $rdsgetcoummu = Redis::get($rdsname);
                if ($user_id != $results['user_id'] && !$rdsgetcoummu) {
                    Redis::setex($rdsname, 3600, $id);
                    (new UserCommu())->where(['id' => $id])->inc('readall', 1)->update();
                }
            }
            $this->result($results, 0, '获取成功');
        }
    }

    public function integrallog()
    {
        $type = $this->request->get('type/d', 1);
        if ($type == 1) {
            $list = (new MoneyLog())->order('id desc');
        } else {
            $list = (new IntergralLog())->order('id desc');
        }
        $list = $list->where(['user_id' =>  $this->request->user_id])
            ->field('info,money,created')
            ->paginate(20, false, ['query' => $this->request->param()]);
        $this->result($list, 0, '查询完成');
    }


    public function rechange()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'money' => 'require|gt:0|float'
            ], [
                'money.require' => '充值金额不能为空',
                'money.gt' => '充值金额必须大于0',
                'money.float' => '充值金额必须是数字',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $results = (new Config())->where(['name' => 'rechange'])->value('value');
            $value = json_decode($results, true);
            $give = 0;
            foreach ($value as $v) {
                if ($data['money'] >= $v['money'] && $give < $v['give']) {
                    $give = $v['give'];
                }
            }
            //支付订单 返回微信信息
            $trade_type = $data['trade_type'] ?? 'JSAPI';
            $ordersn = repayorder(new Payment());
            $wechatarr = [
                'pay_title' => '充值订单支付',
                'payment_id' =>  $ordersn,
                'money' => $data['money'],
                'ip' => $this->request->ip(),
                'user_id' => $this->request->user_id,
                'params' => json_encode(['trade_type' => $trade_type], true)
            ];
            $parmes = [
                'user_id' => $this->request->user_id
            ];
            $parmes = json_encode($parmes, true);
            $list = (new Wechat())->pay($wechatarr);
            if ($list['status'] == true) {
                //存储支付订单记录
                $res = (new Payment())->save(['money' => $data['money'], 'give' => $give, 'type' => 9, 'status' => 1, 'paymentid' => $ordersn, 'ordersn' => 0, 'parmes' => $parmes,]);
                if ($res) {
                    $this->result($list, 0, '获取成功');
                } else {
                    $this->result([], 1, '获取失败,请重试');
                }
            } else {
                $this->result([], 1, $list['msg'] ?? '获取失败');
            }
        } else {
            $results = (new Config())->where(['name' => 'rechange'])->value('value');
            $value = json_decode($results, true);
            $this->result($value, 0, '获取成功');
        }
    }

    public function apply()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (empty($data['type'])) {
                $this->result([], 1, '入驻类型不能为空');
            }
            if ($data['type'] == 1) {
                $validate = new Validate([
                    'name' => 'require',
                    'sex' => 'require|in:1,2',
                    'phone' => 'require',
                    'city' => 'require',
                    'skill' => 'require',
                ], [
                    'name.require' => '用户名不能为空',
                    'sex.require' => '性别不能为空',
                    'sex.require' => '性别类型不正确',
                    'phone.require' => '联系电话不能为空',
                    'city.require' => '意向城市不能为空',
                    'skill.require' => '技能不能为空',
                ]);
            } elseif ($data['type'] == 2 || $data['type'] == 3) {
                $validate = new Validate([
                    'storename' => 'require',
                    'name' => 'require',
                    'phone' => 'require',
                    'city' => 'require',
                ], [
                    'storename.require' => '店铺或公司名称不能为空',
                    'name.require' => '联系人不能为空',
                    'phone.require' => '联系电话不能为空',
                    'city.require' => '意向城市不能为空',
                ]);
            } else {
                $this->result([], 1, '类型错误');
            }
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $data['user_id'] = $this->request->user_id;
            $data['status'] = 1;
            //查询是否已经提交过
            $business = (new Apply())->where(['user_id' => $this->request->user_id, 'type' => $data['type']])->find();
            if (empty($business)) {
                $res = (new Apply())->allowfield(true)->save($data);
            } else {
                $res = (new Apply())->allowfield(true)->save($data, ['id' => $business['id']]);
            }
            if ($res) {
                $this->result([], 0, '提交成功，请等待审核');
            }
            $this->result([], 1, '申请失败，请重试');
        } else {
            $type = $this->request->get('type/d', 0);
            $results = (new Apply())->where(['user_id' => $this->request->user_id, 'type' => $type])->find();
            $this->result($results, 0, '获取成功');
        }
    }

    public function keyend()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'key' => 'require'
        ], [
            'key.require' => '兑换码不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        //查询兑换码是否存在
        $key = (new Pkey())->where(['code' => $data['key'], 'status' => 1])->find();
        if (empty($key)) {
            $this->result([], 1, '兑换码不存在或已被使用');
        }
        //兑换码存在查询活动是否还在继续
        $promo = (new Promo())->where(['id' => $key['promoid'], 'status' => 1, 'type' => 1])->find();
        if (empty($promo)) {
            $this->result([], 1, '兑换码已失效');
        }
        $fors = (int)$promo['coupon'];
        if ($fors <= 0) {
            $this->result([], 1, '兑换码配置错误请联系管理员');
        }
        for ($i = 0; $i < $fors; $i++) {
            $coupons[] = [
                'type' => 3,
                'user_id' => $this->request->user_id,
                'goodsid' => $promo['goodsid'],
                'business' => $promo['agentid'],
                'status' => 1,
                'endtime' => date('Y-m-d H:i:s', time() + 86400 * 10000),
                'promo' => $promo['id'],
                'keyid' => $key['id']
            ];
        }
        Db::startTrans();
        try {
            if (count($coupons) > 0) {
                (new Coupon())->allowfield(true)->saveAll($coupons);
            }
            (new Pkey())->where('id', $key['id'])->update(['status' => 2, 'user_id' => $this->request->user_id]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, $e->getMessage());
        }
        $this->result([], 0, '兑换成功,请注意卡券变动');
    }

    public function receive()
    {
        if ($this->request->isPost()) {
            if ($this->request->user['isnew'] != 1) {
                $this->result([], 1, '已领取或非新用户不可领取');
            }
            $mycoupon = [];
            $mycoupon[] = [
                'user_id' => $this->request->user_id,
                'getmoney' => 100,
                'money' => 30,
                'status' => 1,
                'remark' => '新用户领取赠送',
                'endtime' => date('Y-m-d', time() + 86400 * 30)
            ];
            $mycoupon[] = [
                'user_id' => $this->request->user_id,
                'getmoney' => 199,
                'money' => 10,
                'status' => 1,
                'remark' => '新用户领取赠送',
                'endtime' => date('Y-m-d', time() + 86400 * 30)
            ];
            $mycoupon[] = [
                'user_id' => $this->request->user_id,
                'getmoney' => 599,
                'money' => 50,
                'status' => 1,
                'remark' => '新用户领取赠送',
                'endtime' => date('Y-m-d', time() + 86400 * 30)
            ];
            Db::startTrans();
            try {
                if (count($mycoupon)) {
                    (new Coupon())->saveAll($mycoupon);
                }
                (new Users())->where('id', $this->request->user_id)->update(['isnew' => 2]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '领取失败');
            }
            $this->result([], 0, '领取成功，请优惠券列表查看');
        }
    }

    public function bussiness_res()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (empty($data['type'])) {
                $data['type'] = $data['type'] ?? 0;
            }
            //技工入驻
            if ($data['type'] == 0) {
                $validate = new Validate([
                    'name' => 'require',
                    'sex' => 'require|in:1,2',
                    'mobile' => 'require',
                    'jieshao' => 'require',
                    'cards' => 'require',
                    'xqlist' => 'require',
                    'yxlist' => 'require',
                    'images' => 'require',
                    'images1' => 'require',
                    'images2' => 'require'
                ], [
                    'name.require' => '用户名不能为空',
                    'sex.require' => '性别不能为空',
                    'sex.in' => '性别类型不正确',
                    'jieshao.require' => '个人介绍不能为空',
                    'cards.require' => '身份证号不能为空',
                    'mobile.require' => '联系电话不能为空',
                    'xqlist.require' => '接单小区不能为空',
                    'yxlist.require' => '意向类目不能为空',
                    'images.require' => '个人照不能为空',
                    'images1.require' => '身份证正面不能为空',
                    'images2.require' => '身份证反面不能为空',
                ]);
                if (!$validate->check($data)) {
                    $this->result([], 1, $validate->getError());
                }
                $save = [
                    'user_id' => $this->request->user_id,
                    'jieshao' => $data['jieshao'],
                    'images' => $data['images'],
                    'mobile' => $data['mobile'],
                    'sex' => $data['sex'],
                    'name' => $data['name'],
                    'cards' => $data['cards'],
                    'observe' => $data['images1'],
                    'rbserve' => $data['images2']
                ];
                $people = (new Recpeople())->where('user_id', $save['user_id'])->find();
                $delexq = [];
                Db::startTrans();
                try {
                    if (empty($people)) {
                        $people['id'] = (new Recpeople())->insertGetId($save);
                    } else {
                        (new Recpeople())->allowfield(true)->save($save, ['id' => $people['id']]);
                    }
                    foreach ($data['xqlist'] as $xq) {
                        $commu = (new RecpeopleCommu())->where(['peopleid' => $people['id'], 'commuid' => $xq['id']])->find();
                        if (empty($commu)) {
                            (new RecpeopleCommu())->allowfield(true)->save(['peopleid' => $people['id'], 'commuid' => $xq['id'], 'status' => 2]);
                        } else {
                            if ($commu['status'] != 1) {
                                (new RecpeopleCommu())->where(['id' => $commu['id']])->update(['status' => 2]);
                            }
                        }
                        $delexq[] = $xq['id'];
                    }
                    (new RecpeopleLeimu())->where(['peopleid' => $people['id']])->delete();
                    foreach ($data['yxlist'] as $xq) {
                        (new RecpeopleLeimu())->allowfield(true)->save(['peopleid' => $people['id'], 'leimuid' => $xq['id']]);
                    }
                    if (count($delexq) > 0) {
                        //删除非选中小区
                        (new RecpeopleCommu())->where(['peopleid' => $people['id']])->where('commuid', 'not in', $delexq)->update(['status' => 3]);
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    dump($e->getMessage());
                    $this->result([], 1, '操作失败，请重试');
                }
                $this->result([], 0, '操作成功');
                dump($data);
            }
            //商家入驻
            if ($data['type'] == 1 || $data['type'] == 2) {
                $validate = new Validate([
                    "type" => 'require',
                    "title" => 'require',
                    "name" => 'require',
                    "mobile" => 'require',
                    "xqlist" => 'require',
                    "images" => 'require',
                    "lat" => 'require|gt:0',
                    "lon" => 'require|gt:0',
                    "address" => 'require',
                    "images1" => 'require',
                    "images2" => 'require',
                ], [
                    'type.require' => '类型不能为空',
                    'title.require' => '商家名称不能为空',
                    'name.require' => '联系人姓名不能为空',
                    'mobile.require' => '联系电话不能为空',
                    'xqlist.require' => '服务小区不能为空',
                    'images.require' => '门店LOGO不能为空',
                    'lat.require' => '坐标不能为空',
                    'lon.require' => '坐标不能为空',
                    'lat.gt' => '坐标不能为空',
                    'lon.gt' => '坐标不能为空',
                    'address.require' => '地址不能为空',
                    'images1.require' => '环境图不能为空',
                    'images2.require' => '相关证书不能为空',
                ]);
                if (!$validate->check($data)) {
                    $this->result([], 1, $validate->getError());
                }
                if ($data['type'] == 2 && empty($data['classid'])) {
                    $this->result([], 1, '商家类别不能为空');
                }
                if ($data['type'] == 1) {
                    $data['classid'] = $data['classid'] ?? 0;
                }
                $save = [
                    'user_id' => $this->request->user_id,
                    'touser_id' => 0,
                    'type' => $data['type'],
                    'logo' => $data['images'],
                    'address' => $data['address'],
                    'lat' => $data['lat'],
                    'lon' => $data['lon'],
                    'images' => json_encode($data['images1'], true) ?? '',
                    'yyzz' => json_encode($data['images2'], true) ?? '',
                    'sonstype' => $data['classid'] ?? 0,
                    'name' => $data['name'],
                    'title' => $data['title'],
                    'mobile' => $data['mobile'],
                    'account' => $data['mobile'],
                    'status' => 2,
                ];
                if (!empty($data['code'])) {
                    $touser = (new Users())->where('code', $data['code'])->find();
                    if (empty($touser)) {
                        $this->result([], 1, '推荐码错误');
                    }
                    $save['touser_id'] = $touser['id'];
                }
                $business = (new Business())->where(['user_id' => $save['user_id'], 'type' => $data['type']])->find();
                if (!empty($people) && $people['status'] == 1) {
                    $this->result([], 1, '您已是此类商家(服务商),请前往登录');
                }
                $delexq = [];
                Db::startTrans();
                try {
                    if (empty($business)) {
                        $business['id'] = (new Business())->insertGetId($save);
                    } else {
                        (new Business())->allowfield(true)->save($save, ['id' => $business['id']]);
                    }
                    foreach ($data['xqlist'] as $xq) {
                        $commu = (new BusinessCommu())->where(['businessid' => $business['id'], 'commuid' => $xq['id']])->find();
                        if (empty($commu)) {
                            (new BusinessCommu())->allowfield(true)->save(['businessid' => $business['id'], 'commuid' => $xq['id'], 'status' => 2]);
                        } else {
                            if ($commu['status'] != 1) {
                                (new BusinessCommu())->where(['id' => $commu['id']])->update(['status' => 2]);
                            }
                        }
                        $delexq[] = $xq['id'];
                    }
                    if (count($delexq) > 0) {
                        //删除非选中小区
                        (new BusinessCommu())->where(['businessid' => $business['id']])->where('commuid', 'not in', $delexq)->update(['status' => 3]);
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    dump($e->getMessage());
                    $this->result([], 1, '操作失败，请重试');
                }
                $this->result([], 0, '操作成功');
                dump($data);
            }
            $this->result([], 1, '提交失败，请重试');
        } else {
            $data = $this->request->get();
            $data['type'] = $data['type'] ?? 0;
            $results = [];
            if ($data['type'] == 0) {
                $results = (new Recpeople())->where(['user_id' => $this->request->user_id])->find();
                if (!empty($results)) {
                    $commu = (new RecpeopleCommu())->where(['peopleid' => $results['id']])->select();
                    $xqlist = [];
                    foreach ($commu as $commu) {
                        $agentcommu = (new AgentCommu())->where('id', $commu['commuid'])->value('name');
                        if (!empty($agentcommu)) {
                            $xqlist[] = ['id' => $commu['commuid'], 'name' => $agentcommu];
                        }
                    }
                    $lmus = (new RecpeopleLeimu())->where(['peopleid' => $results['id']])->select();
                    $lmlist = [];
                    foreach ($lmus as $leimu) {
                        $leimu_name = (new PlatSons())->where('id', $leimu['leimuid'])->value('name');
                        if (!empty($leimu_name)) {
                            $lmlist[] = ['id' => $leimu['leimuid'], 'name' => $leimu_name];
                        }
                    }
                    $results['xqlist'] = $xqlist;
                    $results['lmlist'] = $lmlist;
                    if ((new RecpeopleCommu())->where(['peopleid' => $results['id'], 'status' => 1])->count() > 0) {
                        $results['status'] = 1;
                    }
                    if ((new RecpeopleCommu())->where(['peopleid' => $results['id'], 'status' => [1, 2]])->count() <= 0) {
                        $results['status'] = 3;
                    }
                } else {
                    $results['xqlist'] = [];
                    $results['lmlist'] = [];
                    $results['status'] = 3;
                }
            }
            if ($data['type'] == 1 || $data['type'] == 2) {
                $results = (new Business())->where(['user_id' => $this->request->user_id, 'type' => $data['type']])->find();
                $commu = (new BusinessCommu())->where(['businessid' => $results['id']])->select();
                $xqlist = [];
                foreach ($commu as $commu) {
                    $agentcommu = (new AgentCommu())->where('id', $commu['commuid'])->value('name');
                    if (!empty($agentcommu)) {
                        $xqlist[] = ['id' => $commu['commuid'], 'name' => $agentcommu];
                    }
                }
                $results['images'] = json_decode(($results['images'] ?? ''), true) ?? [];
                $results['yyzz'] = json_decode(($results['yyzz'] ?? ''), true) ?? [];
                $results['xqlist'] = $xqlist;
                if ($data['type'] == 2) {
                    $results['class'] = (new BusinessType())->order('ishot desc')->where(['status' => 1])->select();
                }
            }
            $this->result($results, 0, '获取成功');
        }
    }

    public function buyuser()
    {
        $level = $this->request->post('level/d', 1);
        if ($this->request->user['level'] >= $level) {
            $this->result([], 1, '您已经是当前级别会员');
        }
        $level = (new UserLevel())->where('level', $level)->find();
        if (empty($level)) {
            $this->result([], 1, '信息参数错误');
        }
        $level['coupon'] = json_decode($level['coupon'], true);
        if ($level['days'] <= 0) {
            $this->result([], 1, '信息参数错误');
        }
        //支付订单 返回微信信息
        $data = $this->request->post();
        $ordersn = repayorder(new Payment());
        $trade_type = $data['trade_type'] ?? 'JSAPI';
        $wechatarr = [
            'pay_title' => '会员订单支付',
            'payment_id' =>  $ordersn,
            'money' => $level['money'],
            'ip' => $this->request->ip(),
            'user_id' => $this->request->user_id,
            'params' => json_encode(['trade_type' => $trade_type], true)
        ];
        $parmes = [
            'user_id' => $this->request->user_id,
            'zhekou' => $level['zhekou'],
            'money' => $level['money'],
            'coupon' => $level['coupon'],
            'days' => $level['days'],
            'level' => $level['level']
        ];
        $parmes = json_encode($parmes, true);
        $list = (new Wechat())->pay($wechatarr);
        if ($list['status'] == true) {
            //存储支付订单记录
            $res = (new Payment())->save(['money' => $level['money'], 'type' => 2, 'status' => 1, 'paymentid' => $ordersn, 'ordersn' => 0, 'parmes' => $parmes, 'paytype' => 1]);
            if ($res) {
                $this->result($list, 0, '获取成功');
            } else {
                $this->result([], 1, '获取失败,请重试');
            }
        } else {
            $this->result([], 1, $list['msg'] ?? '获取失败');
        }
    }

    public function qrcode()
    {
        $name = 'appcode' . $this->request->user_id . '.png';
        $qcode = url('/uploads/wechat/' . $name, '', '', true);
        $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/wechat/";
        if (!file_exists($path . $name)) {
            $user = $this->request->user;
            $config = config('wechat.');
            $app = Factory::miniProgram($config);
            $rm = $app->app_code->getUnlimit('invite=' . $user['code'], [
                'page'  => '',
                'width' => 600,
            ]);
            if ($rm instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $rm->save($path, $name);
            }
        }
        $this->result(['qrcode' => $qcode, 'code' => $this->request->user['code']], 0, '获取成功');
    }

    public function orderstatus()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'status' => 'require|in:2,4,5'
        ], [
            'id.require' => '订单ID不能为空',
            'status.require' => '状态不能为空',
            'status.in' => '状态不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $order = (new Order())->where(['id' => $data['id'], 'user_id' => $this->request->user_id])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在');
        }
        switch ($data['status']) {
            case '2':
                if ($order['status'] != 1) {
                    $this->result([], 1, '订单不处于支付状态');
                }
                if (empty($data['type'])) {
                    $data['type'] = 1;
                }
                if ($data['type'] == 1) {
                    //支付订单 返回微信信息
                    $trade_type = $data['trade_type'] ?? 'JSAPI';
                    $ordersn = repayorder(new Payment());
                    $wechatarr = [
                        'pay_title' => '服务订单支付',
                        'payment_id' =>  $ordersn,
                        'money' => $order['total'],
                        'ip' => $this->request->ip(),
                        'user_id' => $this->request->user_id,
                        'params' => json_encode(['trade_type' => $trade_type], true)
                    ];
                    $list = (new Wechat())->pay($wechatarr);
                    if ($list['status'] == true) {
                        //存储支付订单记录
                        $res = (new Payment())->save(['money' => $order['total'], 'type' => 1, 'status' => 1, 'paymentid' => $ordersn, 'ordersn' => $order['ordersn']]);
                        if ($res) {
                            $this->result($list, 0, '获取成功');
                        } else {
                            $this->result([], 1, '获取失败,请重试');
                        }
                    } else {
                        $this->result([], 1, $list['msg'] ?? '获取失败');
                    }
                } elseif ($data['type'] == 2) {
                    //货到付款逻辑
                    $res = (new Order())->where('id', $order['id'])->where('status', 1)->update(['status' => 2, 'payment' => $data['type'], 'paytimes' => date('Y-m-d H:i:s')]);
                    if ($res) {
                        $this->result([], 0, '操作成功');
                    } else {
                        $this->result([], 1, '操作失败,请重试');
                    }
                } elseif ($data['type'] == 3) {
                    //查询余额是否足够
                    $user = (new Users())->where(['id' => $this->request->user_id])->find();
                    if ($user['money'] < $order['total']) {
                        $this->result([], 1, '余额不足');
                    }
                    Db::startTrans();
                    try {
                        (new Order())->where('id', $order['id'])->where('status', 1)->update(['status' => 2, 'payment' => $data['type'], 'paytimes' => date('Y-m-d H:i:s')]);
                        if ($order['total'] > 0) {
                            (new Users())->MoneyEdit($user['id'], $user['money'], -$order['total'], 2, $order['id'], '下单购买商品');
                        }
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        dump($e->getMessage());
                        $this->result([], 1, '操作失败，请重试');
                    }
                    $this->result([], 0, '操作成功');
                }
                break;
            case '4':
                if ($order['status'] != 3) {
                    $this->result([], 1, '订单状态不可完成');
                }
                //完成订单
                $res = (new Order())->where('id', $data['id'])->update(['status' => $data['status'], 'finishtimes' => date('Y-m-d H:i:s')]);
                if ($res) {
                    $this->result([], 0, '操作成功');
                }

                $this->result([], 1, '操作失败，请重试');
                break;
            case '5':
                if ($order['status'] != 1 && $order['status'] != 2) {
                    $this->result([], 1, '订单状态不可取消');
                }
                if ($order['shouhou'] != 1) {
                    $this->result([], 1, '订单处于售后状态或已售后');
                }
                //取消
                if ($order['status'] == 1 || $order['status'] == 2) {
                    $shouhou = 1;
                    $status = $data['status'];
                    $tuikuan = 0;
                    $msg = '取消成功';
                    if ($order['status'] == 2 && $order['total'] > 0) {
                        $shouhou = 2;
                        $status = $order['status'];
                        $msg = '订单已提交';
                        $tuikuan = 2;
                    }
                    Db::startTrans();
                    try {
                        if ($order['coupon'] > 0 && $status == 5) {
                            (new Coupon())->where('id', $order['coupon'])->update(['status' => 1]);
                        }
                        (new Order())->where('id', $data['id'])->update([
                            'status' => $status,
                            'text' => $data['text'] ?? '',
                            'shouhou' => $shouhou,
                            'tuikuan' => $tuikuan,
                            'caceltimes' => date('Y-m-d H:i:s')
                        ]);
                        Db::commit();
                        if ($order['status'] == 2 && $order['total'] > 0) {
                            Redis::lPush('tuikuan', $order['id']);
                        }
                    } catch (\Exception $e) {
                        dump($e->getMessage());
                        Db::rollback();
                        $this->result([], 1, '操作失败，请重试');
                    }
                    $this->result([], 0, $msg);
                }
                break;
            default:
                $this->result([], 1, '状态出错');
                break;
        }
    }

    public function goodscompent()
    {
        $goodsid = $this->request->get('goodsid/d', 0);
        $specid = $this->request->get('specid/d', 0);
        $list = (new Compent())->where('goodsid', $goodsid);
        if (!empty($specid)) {
            $list = $list->where('specid', $specid);
        }
        $list = $list->where('star', '>', 3)->field('id,user_id,star,text,images,nickName,avatarUrl,created')->where('isshow', 1)->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            if (empty($lists['nickName'])) {
                $lists['user'] = (new Users())->where('id', $lists['user_id'])->field('nickName,avatarUrl')->find();
            } else {
                $user['nickName'] = $lists['nickName'];
                $user['avatarUrl'] = $lists['avatarUrl'];
                $lists['user'] = $user;
            }
            $lists['images'] = json_decode($lists['images'], true);
        }
        $this->result($list, 0, '获取成功');
    }

    public function compent()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'ordergoodsid' => 'require',
            'star' => 'require',
            'text' => 'require',
        ], [
            'ordergoodsid.require' => '订单规格ID不能为空',
            'star.require' => '评价星级不能为空',
            'text.require' => '评价内容不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        if (!empty($data['images'])) {
            $images = json_decode($data['images'], true) ?? [];
            if (count($images) == 0) {
                $this->result([], 1, '图片上传出错');
            }
        }
        $ordergoods = (new OrderGoods())->where(['id' => $data['ordergoodsid']])->find();
        if (empty($ordergoods)) {
            $this->result([], 1, '订单规格不存在');
        }
        if ($ordergoods['iscompent'] == 2) {
            $this->result([], 1, '您已评价，无需重复评价');
        }
        $order = (new Order())->where('ordersn', $ordergoods['ordersn'])->where('user_id', $this->request->user_id)->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在');
        }
        if ($order['status'] != 4) {
            $this->result([], 1, '订单状态未完成');
        }
        Db::startTrans();
        try {
            (new OrderGoods())->where(['id' => $data['ordergoodsid']])->update(['iscompent' => 2]);
            (new Compent())->allowfield(true)->save([
                'user_id' => $this->request->user_id,
                'orderid' => $order['id'],
                'ordergoodsid' => $ordergoods['id'],
                'goodsid' => $ordergoods['goodsid'],
                'specid' => $ordergoods['goodspecid'],
                'businessid' => $ordergoods['businessid'],
                'star' => $data['star'] ?? 5,
                'text' => $data['text'] ?? '很不错!',
                'images' => $data['images'] ?? ''
            ]);
            $ordercount = (new OrderGoods())->where(['ordersn' => $ordergoods['ordersn'], 'iscompent' => 1])->count();
            if ($ordercount == 0) {
                (new Order())->where('ordersn', $ordergoods['ordersn'])->update(['ispj' => 2]);
            }
            Db::commit();
            if ($data['star'] > 3) {
                (new Goods())->where('id', $ordergoods['goodsid'])->setInc('goodspj');
            }
        } catch (\Exception $e) {
            dump($e->getMessage());
            Db::rollback();
            $this->result([], 1, '评价失败');
        }
        $this->result([], 0, '评价成功');
    }

    public function orderdetail()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new Order())->where('id', $id)->field('coupon,paytimes,fwtimes,finishtimes,caceltimes', true)->find();
        if ($list) {
            $list['images'] = json_decode($list['images'] ?? '', true) ?? [];
            $list['leimu_name'] = (new PlatSons())->where('id', $list['leimu'])->value('name') ?? '';
            $list['xiaoquaddress'] = (new AgentCommu())->where('id', $list['xiaoquid'])->value('address') ?? '';
            $list['status_text'] = $list->status_text;
            $list['province_text'] = (new Region())->where(['area_code' => $list['province']])->value('name');
            $list['city_text'] = (new Region())->where(['area_code' => $list['city']])->value('name');
            $list['area_text'] = (new Region())->where(['area_code' => $list['area']])->value('name');
            $list['street_text'] = (new Region())->where(['id' => $list['street']])->value('name');
            $goods = (new OrderGoods())->where('ordersn', $list['ordersn'])->field('id,ordersn,images,number,title,name,goodsid,goodspecid,price,unmit,iscompent')->select();
            foreach ($goods as $good) {
                $good['images'] = json_decode($good['images'], true);
            }
            $list['good'] = $goods;
        }
        $this->result($list, 0, '获取成功');
    }

    public function getorders()
    {
        $ordersn = $this->request->get('ordersn/d', 0);
        $list = (new OrderGoods())->where(['ordersn' => $ordersn])->select();
        $havegoods = [];
        foreach ($list as $lists) {
            $goods = (new Goods())
                ->alias('g')
                ->distinct(true)
                ->join('business b', 'g.businessid = b.id')
                ->join('goods_spec gs', 'gs.goodid= g.id')
                ->where(['gs.id' => $lists['goodspecid'], 'gs.isdel' => 1, 'g.isSale' => 1, 'g.isdel' => 1, 'b.status' => 1])
                ->field('g.id,g.type,g.title,g.starbuy,g.images,g.times,gs.id as specid,gs.price,gs.name,gs.stock,gs.unmit')->find();
            if (!empty($goods)) {
                $goods['number'] = $lists['number'];
                if ($lists['number'] < $goods['starbuy']) {
                    $goods['number'] = $goods['starbuy'];
                }
                $goods['images'] = json_decode($goods['images'], true);
                $havegoods = $goods;
            }
        }
        $this->result($havegoods, 0, '获取成功');
    }

    public function getcoupon()
    {
        $data = $this->request->get();
        $list = (new Coupon())->where(['user_id' => $this->request->user_id, 'status' => 1])->order('created desc')->select();
        $getgoods = array_column($list->toArray(), 'goodsid');
        $total = 0;
        $businessid = 0;
        $money = 0; //单品最大金额
        if (!empty($data['specid'])) {
            $data['specid'] = json_decode($data['specid'] ?? '', true);
            if (empty($data['specid'])) {
                $this->result([], 1, '规格数据错误');
            }
            foreach ($data['specid'] as $spec) {
                if (empty($spec['id'])  || empty($spec['number'])) {
                    continue;
                }
                //查询规格是否存在
                $goodspec = (new GoodsSpec())->where(['isdel' => 1, 'id' => $spec['id']])->find();
                if (empty($goodspec)) {
                    continue;
                }
                //判断商品是否下架
                $goods = (new Goods())->where(['isdel' => 1, 'isSale' => 1, 'id' => $goodspec['goodid']])->find();
                if (empty($goods)) {
                    dump(1);
                    continue;
                }
                //判断商户是否正常
                $business = (new Business())->where(['id' => $goods['businessid'], 'status' => 1])->find();
                if (empty($business)) {
                    continue;
                }
                $businessid = $business['id'];
                $total += $goodspec['price'] * $spec['number'];
                if ($money < $goodspec['price'] && in_array($goods['id'], $getgoods) && $goods['id'] > 0) {
                    $money = $goodspec['price'];
                }
            }
        }
        foreach ($list as $lists) {
            $lists['title'] = '优惠卡';
            $lists['iscan'] = 1;
            if ($lists['type'] == 3) {
                $lists['title'] = (new Business())->where('id', $lists['business'])->value('title') ?? '';
                $goodids = (new Goods())->where('id', $lists['goodsid'])->value('title');
                $lists['title'] = $goodids . ' 【' . $lists['title'] . '】';
                $lists['getmoney'] = 0;
                if ($businessid == $lists['business']) {
                    $lists['iscan'] = 2;
                }
                if ($lists['goodsid'] > 0) {
                    $lists['money'] = $money;
                } else {
                    $lists['money'] = 0;
                    $lists['iscan'] = 1;
                }
                $lists['endtime'] = '----';

                if ($money <= 0) {
                    $lists['iscan'] = 1;
                }
            }
            if ($lists['type'] == 2) {
                $lists['title'] = (new Business())->where('id', $lists['business'])->value('title') ?? '';
                if ($businessid == $lists['business'] && $total >= $lists['getmoney']) {
                    $lists['iscan'] = 2;
                }
            }
            if ($lists['type'] == 1) {
                if ($total >= $lists['getmoney']) {
                    $lists['iscan'] = 2;
                }
            }
        }
        //优惠券减免
        $this->result($list, 0, '获取成功');
    }

    public function putorder()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'ordertype' => 'require|in:1,2,3',
            'types' => 'require|in:1,2',
            'specid' => 'require',
            'xiaoquid' => 'require',
        ], [
            'ordertype.require' => '产品类型不能为空',
            'ordertype.in' => '产品类型不正确',
            'types.require' => '是否配送类型不能为空',
            'types.in' => '是否配送类型不能为空',
            'specid.require' => '规格ID不能为空',
            'xiaoquid.require' => '小区ID不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $data['times'] = date('Y-m-d H:i', strtotime($data['times'] ?? '')) ?? date('Y-m-d H:i:s');
        $data['specid'] = json_decode($data['specid'] ?? '', true);
        if (empty($data['specid'])) {
            $this->result([], 1, '规格数据错误');
        }
        if (!empty($data['cartid'])) {
            $data['cartid'] = json_decode($data['cartid'] ?? '', true) ?? [];
        }
        if ($data['types'] == 1 && $data['ordertype'] != 3) {
            if (empty($data['addressid'])) {
                $this->result([], 1, '联系人信息不存在');
            }
            //查询地址是否存在
            $address = (new Address())->where(['user_id' => $this->request->user_id, 'id' => $data['addressid']])->find();
            if (empty($address)) {
                $this->result([], 1, '联系人信息不存在');
            }
        }
        if ($data['ordertype'] == 3) {
            $data['jjprice'] =  $data['jjprice'] ?? 0;
            if ($data['times'] <= date('Y-m-d H:i:s')) {
                $data['times'] = date('Y-m-d H:i:s', time() + 1800);
            }
            if (empty($data['remark'])) {
            }
            $data['images'] = json_encode($data['images'], true) ?? '';
        } else {
            $data['jjprice'] = 0;
        }
        $order = [
            'leimu' => 0,
            'ordertype' => $data['ordertype'],
            'types' => $data['types'],
            'xiaoquid' => $data['xiaoquid'],
            'user_id' => $this->request->user_id,
            'ordersn' => reordersn(new Order()),
            'businessid' => 0,
            'name' => $address['name'] ?? '',
            'mobile' => $address['mobile'] ?? '',
            'province' => $address['province'] ?? '',
            'city' => $address['city'] ?? '',
            'area' => $address['area'] ?? '',
            'street' => $address['street'] ?? '',
            'getaddress' => $address['getaddress'] ?? '',
            'address' => $address['address'] ?? '',
            'putaddress' => $data['address1'] ?? '',
            'sendaddress' => $data['address2'] ?? '',
            'images' => $data['images'] ?? '',
            'lat' => $address['lat'] ?? '',
            'lon' => $address['lon'] ?? '',
            'total' => 0,
            'jjprice' => $data['jjprice'] ?? 0,
            'coupon' => $data['coupon'] ?? 0,
            'times' => $data['times'],
            'remark' => $data['remark'] ?? '',
            'sendmoney' => 0,
            'coupontotal' => 0,
            'othertotal' => 0,
            'total' => 0,
            'ptotal' => 0
        ];
        $ordergoods = [];
        $sends = 0; //起送金额
        $maxmoney = 0;
        if (!empty($data['coupon'])) {
            $coupon = (new Coupon())->where(['id' => $data['coupon'], 'user_id' => $this->request->user_id, 'status' => 1])->find();
        }
        foreach ($data['specid'] as $spec) {
            if (empty($spec['id'])  || empty($spec['number'])) {
                $this->result([], 1, '规格参数错误');
            }
            //查询规格是否存在
            $goodspec = (new GoodsSpec())->where(['isdel' => 1, 'id' => $spec['id']])->find();
            if (empty($goodspec)) {
                $this->result([], 1, '规格已下架，请重新选择下单');
            }
            //判断商品是否下架
            $goods = (new Goods())->where(['isdel' => 1, 'isSale' => 1, 'id' => $goodspec['goodid']])->find();
            if (empty($goods)) {
                $this->result([], 1, '商品已下架');
            }
            $order['leimu'] = $goods['sonsid'];
            // if ($goods['type'] == 3 && $goodspec['stock'] < $spec['number']) {
            //     $this->result([], 1, '库存不足');
            // }
            //判断商户是否正常
            $business = (new Business())->where(['id' => $goods['businessid']])->find();
            if (empty($business) || $business['status'] != 1) {
                $this->result([], 1, '商家已下架');
            }
            if ($business['shows'] != 1) {
                $this->result([], 1, '超出服务范围');
            }
            // if ($business['type'] == 1) {
            //     $fwtime = $business['fwtime'] ?? '00:00 - 24:00';
            //     $fwtime = explode('-', $fwtime);
            //     $start = $fwtime[0] ?? '00:00';
            //     $end = $fwtime[1] ?? '22:00';
            //     //最早时间计算
            //     $zuizao = date('H', time() + 1800 + $goods['times'] * 60) . ':00';
            //     //如果超越了营业时间可预约明天
            //     if (strtotime($zuizao) > strtotime($end)) {
            //         $zuizao = date('Y-m-d ', time() + 86400) . $start;
            //     } else {
            //         $zuizao = date('Y-m-d ') . $zuizao;
            //     }
            //     if ($data['times'] < $zuizao) {
            //         $this->result([], 1, '预约时间不能早于' . $zuizao);
            //     }
            // }
            if (empty($order['businessid'])) {
                $order['businessid'] = $goods['businessid'];
            } elseif ($order['businessid'] != $goods['businessid']) {
                $this->result([], 1, '不同商家商品不可同时下单');
            }
            $sends = $business['sends'];
            //查找下面有没有相关服务人员
            $order['ptotal'] += $goodspec['price'] * $spec['number'];
            $ordergoods[] = [
                'ordersn' => $order['ordersn'],
                'businessid' => $goods['businessid'],
                'classid' => $goods['classid'],
                'sonsid' => $goods['sonsid'],
                'goodsid' => $goods['id'],
                'goodspecid' => $goodspec['id'],
                'title' => $goods['title'],
                'images' => $goods['images'],
                'name' => $goodspec['name'],
                'number' =>  $spec['number'],
                'unmit' => $goodspec['unmit'],
                'price' =>   $goodspec['price'],
                'total' => floor($spec['number'] * $goodspec['price'] * 100) / 100
            ];
            if ($maxmoney < $goodspec['price'] && !empty($coupon) && $goods['id'] == $coupon['goodsid']) {
                $maxmoney = $goodspec['price'];
            }
        }
        if (empty($order['leimu']) && !empty($order['ordertype'] != 2)) {
            $this->result([], 1, '请选择类目或服务项目');
        }
        $order['qusong'] = (new PlatSons())->where('id', $order['leimu'])->value('qusong') ?? 0;
        if ($order['ordertype'] == 3) {
            if (empty($order['leimu'])) {
                $this->result([], 1, '服务项目不能为空');
            }
            if ($order['qusong'] == 2 && (empty($order['putaddress']) || empty($order['sendaddress']))) {
                $this->result([], 1, '请填写取送件地址');
            }
            if ($order['qusong'] == 1 && empty($order['putaddress'])) {
                $this->result([], 1, '请填写服务地址');
            }
        }
        if ($business['type'] != 2) {
            if (count($ordergoods) > 1) {
                $this->result([], 1, '当前类别一次只能下单个产品');
            }
        }
        if ($order['total'] < $sends && $data['types'] == 1) {
            $this->result([], 1, '产品总价低于商家服务金额' . $sends . '元，下单失败');
        }
        $order['total'] = $order['ptotal'];
        if ($order['ordertype'] == 2 && $order['types'] == 1) {
            $order['sendmoney'] = $business['sendmoney'] ?? 0;
        }
        //优惠券减免
        if (!empty($data['coupon'])) {
            $coupon = (new Coupon())->where(['id' => $data['coupon'], 'user_id' => $this->request->user_id, 'status' => 1])->find();
            if (empty($coupon)) {
                $this->result([], 1, '优惠券不存在或已使用');
            }
            if ($coupon['type'] == 3 && $coupon['goodsid'] == 0) {
                $this->result([], 1, '优惠券错误');
            }
            if (($coupon['type'] == 2 || $coupon['type'] == 3) && $coupon['business'] != $order['businessid']) {
                $this->result([], 1, '优惠券在该商户平台不可用');
            }
            if ($coupon['type'] == 3) {
                $coupon['getmoney'] = 0;
                $coupon['money'] = $maxmoney;
            }
            if ($coupon['getmoney'] > $order['ptotal']) {
                $this->result([], 1, '优惠券未达到使用条件');
            }
            if ($coupon['money'] > $order['total']) {
                $order['coupontotal'] = $order['total'];
                $order['total'] = 0;
            } else {
                $order['coupontotal'] = $coupon['money'];
                $order['total'] -= $coupon['money'];
            }
        }
        if (count($ordergoods) < 1 || count($order) < 1) {
            $this->result([], 1, '结算出错,请重试');
        }
        $order['ptotal'] += $order['sendmoney'];
        $order['total'] += $order['sendmoney'];
        $order['total'] += $order['jjprice'];
        $order['ptotal'] += $order['jjprice'];
        if ($order['total'] <= 0) {
            $order['total'] = 0;
            $order['status'] = 2;
        }
        Db::startTrans();
        try {
            $id = (new Order())->insertGetId($order);
            (new OrderGoods())->allowfield(true)->saveAll($ordergoods);
            if (!empty($data['cartid'])) {
                (new Cart())->where(['id' => $data['cartid'], 'user_id' => $this->request->user_id])->delete();
            }
            if (!empty($coupon) && $maxmoney > 0) {
                (new Coupon())->where(['id' => $coupon['id'], 'user_id' => $this->request->user_id, 'status' => 1])->update(['status' => 3]);
            }
            Db::commit();
        } catch (\Exception $e) {
            dump($e->getMessage());
            Db::rollback();
            $this->result([], 1, '下单失败');
        }
        $this->result(['id' => $id], 0, '下单成功');
    }

    public function orderlist()
    {
        $status = $this->request->get('status/d', '');
        $ordertype = $this->request->get('ordertype/d', '');
        $list = (new Order())->order('id desc');
        if (!empty($status)) {
            $list = $list->where('status', $status);
        }
        if (!empty($ordertype)) {
            $list = $list->where('ordertype', $ordertype);
        }
        $list = $list->where('user_id', $this->request->user_id)->field('id,leimu,images,xiaoquid,putaddress,sendaddress,qusong,types,ordertype,ordersn,businessid,status,total,ptotal,shouhou,tuikuan,created,ispj,payment')->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $lists['tnumber'] = 0;
            $lists['business_name'] = (new Business())->where('id', $lists['businessid'])->value('title');
            $ordergoods = (new OrderGoods())->where(['ordersn' => $lists['ordersn']])->field('id,title,name,unmit,goodspecid,images,number,iscompent,price')->select();
            foreach ($ordergoods as $goods) {
                $lists['tnumber'] += $goods['number'];
                $goods['images'] = json_decode($goods['images'] ?? '', true);
            }
            $lists['goods'] = $ordergoods;
            $lists['status_text'] = $lists->status_text;
            $lists['images'] = json_decode($lists['images'], true) ?? [];
            $lists['leimu_name'] = (new PlatSons())->where('id', $lists['leimu'])->value('name') ?? '';
            $lists['xiaoquaddress'] = (new AgentCommu())->where('id', $lists['xiaoquid'])->value('address') ?? '';
        }
        $this->result($list, 0, '获取成功');
    }

    public function cart()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'goodsid' => 'require',
                'specid' => 'require',
                'number' => 'require',
            ], [
                'goodsid.require' => '商品ID不能为空',
                'specid.require' => '商品规格不能为空',
                'number.require' => '商品数目不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if ($data['number'] <= 0) {
                $mycart = (new Cart())->where(['specid' => $data['specid'], 'user_id' => $this->request->user_id])->find();
                if (!empty($mycart)) {
                    $result = (new Cart())->where(['user_id' => $this->request->user_id, 'id' => $mycart['id']])->delete();
                    if ($result) {
                        $this->result([], 0, '操作成功');
                    }
                    $this->result([], 1, '操作失败');
                }
                $this->result([], 0, '操作成功');
            }
            $goods = (new Goods())->where(['id' => $data['goodsid'], 'isSale' => 1, 'isdel' => 1])->find();
            if (empty($goods)) {
                $this->result([], 1, '商品已下架');
            }
            $business = (new Business())->where(['id' => $goods['businessid'], 'status' => 1])->find();
            if (empty($business)) {
                $this->result([], 1, '商家已下架');
            }
            if ($business['type'] == 1) {
                $this->result([], 1, '商家类型不支持商家购物车');
            }
            $goodsspec = (new GoodsSpec())->where(['isdel' => 1, 'goodid' => $goods['id'], 'id' => $data['specid']])->find();
            if (empty($goodsspec)) {
                $this->result([], 1, '规格产品已下架');
            }
            //查询是否已经添加购物车
            $mycart = (new Cart())->where(['specid' => $data['specid'], 'user_id' => $this->request->user_id])->find();
            // //购物车商品数量不能超过20个
            // if (empty($mycart)) {
            //     $carts = (new Cart())->where(['user_id' => $this->request->user_id])->count();
            //     if ($carts >= 50) {
            //         $this->result([], 1, '您的购物车产品数量已达到50个,请先结算或清空购物车');
            //     }
            // }
            $number = (int)$data['number'] ?? 0;
            $goods['starbuy'] = $goods['starbuy'] > 1 ? $goods['starbuy'] : 1;
            if (!empty($data['type']) && $data['type'] == 2) {
                $number = $data['number'];
            } else {
                if (!empty($mycart)) {
                    $number += $mycart['number'];
                }
            }
            if ($number <  $goods['starbuy']) {
                $this->result([], 1, '起购数量不能低于' . $goods['starbuy']);
            }
            $save = [
                'user_id' => $this->request->user_id,
                'business' => $business['id'],
                'goodsid' => $goods['id'],
                'specid' => $goodsspec['id'],
                'number' => $number
            ];
            if (!empty($mycart)) {
                $res =  (new Cart())->allowfield(true)->save($save, ['id' => $mycart['id']]);
            } else {
                $res =  (new Cart())->allowfield(true)->save($save);
            }
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败');
        } else {
            $businessid = $this->request->get('businessid/d', 0);
            $list = (new Cart())->where(['user_id' => $this->request->user_id, 'business' => $businessid])->select();
            $result = [
                'data' => [],
                'total' => 0,
                'count' => 0,
            ];
            foreach ($list as $lists) {
                $good = (new Goods())->where(['id' => $lists['goodsid']])->where(['isSale' => 1, 'isdel' => 1])->field('id,title,images,starbuy')->find();
                if (!empty($good)) {
                    $good['images'] = json_decode($good['images'], true);
                    $good['goodspec'] = (new GoodsSpec())->where('isdel', 1)->where(['id' => $lists['specid']])->field('id,name,price,unmit')->find();
                    $good['numbers'] = $lists['number'];
                    if (!empty($good['goodspec'])) {
                        $result['count'] += $lists['number'];
                        $result['total'] += $lists['number'] * $good['goodspec']['price'];
                        $result['data'][] = $good;
                    }
                }
            }
            $this->result($result, 0, '获取成功');
        }
    }

    public function cart_del()
    {
        $id = $this->request->post('id', '');
        $id = json_decode($id, true);
        if (count($id) <= 0) {
            $this->result([], 1, '操作失败');
        }
        $cartmodel = new Cart();
        $result = $cartmodel->where(['user_id' => $this->request->user_id, 'id' => $id])->delete();
        if ($result) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败');
    }

    public function info()
    {
        $user = $this->request->user;
        $rechange = (new Config())->where(['name' => 'rechange'])->value('value');
        $rechange = json_decode($rechange, true) ?? [];
        $people = (new Recpeople())->where('user_id', $user['id'])->find();
        $jishi = 0;
        if (!empty($people)) {
            $commu = (new RecpeopleCommu())->where(['peopleid' => $people['id'], 'status' => 1])->find();
            if (!empty($commu)) {
                $jishi = $people['id'];
            }
        }
        $result = [
            'id' => $user['id'],
            'code' => $user['code'],
            'nickName' => $user['nickName'],
            'gender' => $user['gender'],
            'avatarUrl' => $user['avatarUrl'],
            'mobile' => $user['mobile'],
            'money' => (float)$user['money'],
            'integral' => (float)$user['integral'],
            'coupn' => (new Coupon())->where(['user_id' => $this->request->user_id, 'status' => 1])->count(),
            'rechange' => $rechange,
            'agent' => (new Agent())->where(['mobile' => $user['mobile'], 'status' => 1])->value('id') ?? 0,
            'shangjia' => (new Business())->where(['user_id' => $user['id'], 'type' => 2, 'status' => 1])->value('id') ?? 0,
            'fuwushang' => (new Business())->where(['user_id' => $user['id'], 'type' => 1, 'status' => 1])->value('id') ?? 0,
            'jishi' => $jishi,
        ];
        $this->result($result, 0, '获取成功');
    }

    public function login()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'code' => 'require',
            'iv' => 'require',
            'encryptedData' => 'require',
        ], [
            'code.require' => '微信授权码不能为空',
            'iv.require' => 'IV数据不能为空',
            'encryptedData.require' => 'encryptedData数据不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $model = new Users();
        $config = config('wechat.');
        $app = Factory::miniProgram($config);
        try {
            $res = $app->auth->session($data['code']);
        } catch (\Exception $e) {
            $this->result([], 1, '信息错误');
        }
        $time = $config['tokenExpireHours'];
        if (empty($res['session_key']) || empty($res['openid'])) {
            $this->result([], 1, '登录失败,请重试');
        }
        try {
            $decryptedData = $app->encryptor->decryptData($res['session_key'], $data['iv'], $data['encryptedData']);
        } catch (\Exception $e) {
            $this->result([], 1, $e->getMessage());
        }
        if (empty($decryptedData['phoneNumber'])) {
            $this->result([], 1, '登录失败,请重试');
        }
        //判断用户是否已经注册
        $user = $model->where('mobile', $decryptedData['phoneNumber'])->find();
        $save = [
            'unionid' => $res['unionid'] ?? '',
            'session_key' => $res['session_key'] ?? '',
            'openid' => $res['openid'] ?? '',
            'mobile' => $decryptedData['phoneNumber'] ?? '',
            'gender' => $decryptedData['gender'] ?? 0,
            'province' => $decryptedData['province'] ?? '',
            'city' => $decryptedData['city'] ?? '',
            'country' => $decryptedData['country'] ?? '',
        ];
        if ($user) {
            $res2 = (new Users())->allowfield(true)->save($save, ['id' => $user['id']]);
        } else {
            $save['code'] = recode($model);
            $res2 = (new Users())->allowfield(true)->save($save);
            $user = (new Users())->where('openid', $res['openid'])->find();
        }
        if ($res2 && !empty($user)) {
            $token = 'user_' . md5(time() . $user['code']);
            Redis::setex($token, $time, $user['id']);
            $this->result(['token' => $token], 0, '登录成功');
        }

        $this->result([], 1, '登录失败');
    }


    //微信APP账号登录|注册
    public function login3()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'unionid' => 'require'
        ], [
            'unionid.require' => '微信授权码不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        if (!empty($data['unionid'])) {
            $user = (new Users())->where('unionid', $data['unionid'])->find();
            $res['session_key'] = md5(time() . md5($data['unionid']));
            $config = config('wechat3.');
            $time = $config['tokenExpireHours'];
            if (!empty($user)) {
                Redis::setex($res['session_key'], $time, $user['id']);
            } else {
                $savearr = [
                    'openid' => $data['openid'] ?? '',
                    'unionid' => $data['unionid'] ?? '',
                    'code' => recode(new Users()),
                    'avatarUrl' => $data['logo'] ?? '',
                    'nickName' => preg_replace('/[\xf0-\xf7].{3}/', '', $data['nickname'] ?? '')
                ];
                try {
                    $rs = (new Users())->insertGetId($savearr);
                } catch (\Exception $e) {
                    dump($e->getMessage());
                    Log::write($savearr, 'weichats');
                    Log::write($e->getMessage(), 'weichats');
                    Log::write('==============分割线=============', 'weichats');
                    $this->result([], 1, '操作失败,请联系管理员');
                }
                if ($rs) {
                    Redis::setex($res['session_key'], $time, $rs);
                }
            }
            $this->result(['token' => $res['session_key'], 'expire' => $time], 0, '登录成功');
        } else {
            $this->result([], 1, '登录失败');
        }
    }



    public function address()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
                'mobile' => 'require',
                'street' => 'require',
                'address' => 'require',
                'is_default' => 'require|in:1,2',
                'getaddress' => 'require',
                'lat' => 'require',
                'lon' => 'require',
            ], [
                'name.require' => '联系人姓名不能为空',
                'mobile.require' => '联系人电话不能为空',
                'street.require' => '街道ID不能为空',
                'address.require' => '具体地址不能为空',
                'getaddress.require' => '定位地址不能为空',
                'is_default.require' => '默认类型不能为空',
                'is_default.in' => '默认类型不正确',
                'lat.require' => '经度不能为空',
                'lon.require' => '纬度不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $regionmodel = new Region();
            $street = $regionmodel->where(['id' => $data['street'], 'level' => 4])->find();
            if (!$street) {
                $this->result([], 1, '街道编码出错');
            }
            $area = $regionmodel->where(['id' => $street['parent_id'], 'level' => 3])->find();
            if (!$area) {
                $this->result([], 1, '区域编码出错');
            }
            $city = $regionmodel->where(['id' => $area['parent_id'], 'level' => 2])->find();
            if (!$city) {
                $this->result([], 1, '城市编码出错');
            }
            $province = $regionmodel->where(['id' => $city['parent_id'], 'level' => 1])->find();
            if (!$province) {
                $this->result([], 1, '省份编码出错');
            }
            $data['street'] = $street['id'];
            $data['area'] = $area['area_code'];
            $data['city'] = $city['area_code'];
            $data['province'] = $province['area_code'];
            $data['user_id'] = $this->request->user_id;
            $addressmodel = new Address();
            if ($data['is_default'] == 2) {
                $addressmodel->where(['user_id' => $data['user_id'], 'is_default' => 2])->update(['is_default' => 1]);
            }
            if (!empty($data['id'])) {
                $res = $addressmodel->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = $addressmodel->allowfield(true)->save($data);
            }
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败');
        } else {
            $addressmodel = new Address();
            $regionmodel = new Region();
            $result = $addressmodel->where('user_id', $this->request->user_id)->order('is_default desc')->field('user_id,created', true)->select();
            foreach ($result as $results) {
                $results['province_name'] = $regionmodel->where(['area_code' => $results['province'], 'level' => 1])->value('name');
                $results['city_name'] = $regionmodel->where(['area_code' => $results['city'], 'level' => 2])->value('name');
                $results['area_name'] = $regionmodel->where(['area_code' => $results['area'], 'level' => 3])->value('name');
                $results['street_name'] = $regionmodel->where(['id' => $results['street'], 'level' => 4])->value('name');
            }
            $this->result($result, 0, '操作成功');
        }
    }


    public function address_del()
    {
        $id = $this->request->post('id/d', 0);
        $addressmodel = new Address();
        $result = $addressmodel->where(['user_id' => $this->request->user_id, 'id' => $id])->delete();
        if ($result) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败');
    }
}
